{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Accessing and managing groups\n",
    "Groups are collaborative spaces in your GIS where your users share related content. Groups support metadata allowing you to customize them as per their theme. You can add users to a group with different group related privileges. Refer to the [topic on groups](https://doc.arcgis.com/en/arcgis-online/share-maps/groups.htm) to learn more about them.\n",
    "\n",
    "In the `gis` module, groups are represented using instances of `Group` class. Similar to `Items`, `Users`, `Roles`, an instance of a resource manager class called `GroupManager` is used to create, search and provide you access to `Group` objects. As with other resource manager objects, you would not create an instance of `GroupManager` using its constructor, but access it from the `groups` property of the `GIS` object.\n",
    "\n",
    "In this guide, we will observe:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "toc": true
   },
   "source": [
    "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n",
    "<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Searching-for-groups\" data-toc-modified-id=\"Searching-for-groups-1\">Searching for groups</a></span></li><li><span><a href=\"#Properties-of-a-group\" data-toc-modified-id=\"Properties-of-a-group-2\">Properties of a group</a></span></li><li><span><a href=\"#Creating-new-groups\" data-toc-modified-id=\"Creating-new-groups-3\">Creating new groups</a></span><ul class=\"toc-item\"><li><span><a href=\"#Sharing-content-to-groups\" data-toc-modified-id=\"Sharing-content-to-groups-3.1\">Sharing content to groups</a></span></li></ul></li><li><span><a href=\"#Managing-your-groups\" data-toc-modified-id=\"Managing-your-groups-4\">Managing your groups</a></span><ul class=\"toc-item\"><li><span><a href=\"#Listing-contents-of-the-group\" data-toc-modified-id=\"Listing-contents-of-the-group-4.1\">Listing contents of the group</a></span></li><li><span><a href=\"#Adding-users-to-the-group\" data-toc-modified-id=\"Adding-users-to-the-group-4.2\">Adding users to the group</a></span></li><li><span><a href=\"#Removing-users-from-a-group\" data-toc-modified-id=\"Removing-users-from-a-group-4.3\">Removing users from a group</a></span></li><li><span><a href=\"#Listing-users-belonging-to-a-group\" data-toc-modified-id=\"Listing-users-belonging-to-a-group-4.4\">Listing users belonging to a group</a></span></li><li><span><a href=\"#Updating-a-group\" data-toc-modified-id=\"Updating-a-group-4.5\">Updating a group</a></span></li><li><span><a href=\"#Terminating-a-group\" data-toc-modified-id=\"Terminating-a-group-4.6\">Terminating a group</a></span></li></ul></li></ul></div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"searching-for-groups\"></a>\n",
    "## Searching for groups\n",
    "You can search for groups by using the `search()` method of `GroupManager` object. The `search()` method accepts standard [ArcGIS REST API queries](https://developers.arcgis.com/rest/users-groups-and-items/search-reference/). To illustrate this better, let us connect to ArcGIS Online anonymously and search for public groups that have the word 'water' in the title."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 108,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[<Group title:\" Mexican Water Chapter COVID19 Hub Content\" owner:wy_mex>,\n",
       " <Group title:\"\"High Water Mark\" Initiative\" owner:risson>,\n",
       " <Group title:\"(S)ken je sloot Waternet\" owner:sjoerd.hoekstra@tauw.com_tauw>,\n",
       " <Group title:\"(T) Lewisboro - Lake Waccabuc Water Quality Survey\" owner:gdesantis_Barton>,\n",
       " <Group title:\"03383727 World Water Test NeSc-Content\" owner:riwo4dechsupport>,\n",
       " <Group title:\"100415487_001_Thames_Water_Charvil\" owner:Edward.Wibberley@mottmac.com_mottmac_EMA>,\n",
       " <Group title:\"11134352_SUSQTWP_STORM_WATER\" owner:risson>,\n",
       " <Group title:\"2.2: Inhoud Geodata portaal - Waterschap Aa en Maas\" owner:aaenmaas>,\n",
       " <Group title:\"2013 Audubon Center Water Quality Study\" owner:williamtraddhymes>,\n",
       " <Group title:\"2013 Audubon Water Quality\" owner:andcardoza2013>,\n",
       " <Group title:\"2013 Audubon Water Quality\" owner:nicboucher12>,\n",
       " <Group title:\"2013 Audubon Water Quality Study\" owner:kylwalker>,\n",
       " <Group title:\"2013 Audubon Water Quality Study\" owner:bdhsaudubon>,\n",
       " <Group title:\"2013 Audubon Water Quality Study\" owner:Bradlynn>,\n",
       " <Group title:\"2017 Esri Water Technical Workshops\" owner:Deilson_EsriWater>]"
      ]
     },
     "execution_count": 108,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from arcgis.gis import GIS\n",
    "ago_gis = GIS()\n",
    "urban_groups = ago_gis.groups.search('title:water', max_groups=15)\n",
    "urban_groups"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "source": [
    "The `search()` method returns a list of objects of type `arcgis.gis.Group`. When using the Jupyter notebook environment, `Group` objects can be represented in rich HTML with their thumbnail and metadata information."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div class=\"9item_container\" style=\"height: auto; overflow: hidden; border: 1px solid #cfcfcf; border-radius: 2px; background: #f6fafa; line-height: 1.21429em; padding: 10px;\">\n",
       "                    <div class=\"item_left\" style=\"width: 210px; float: left;\">\n",
       "                       <a href='https://www.arcgis.com/home/group.html?id=79d753815619465c9093829d3d8149a8' target='_blank'>\n",
       "                        <img src='https://www.arcgis.com/sharing/rest/community/groups/79d753815619465c9093829d3d8149a8/info/thumbnail.png' class=\"itemThumbnail\">\n",
       "                       </a>\n",
       "                    </div>\n",
       "\n",
       "                    <div class=\"item_right\" style=\"float: none; width: auto; overflow: hidden;\">\n",
       "                        <a href='https://www.arcgis.com/home/group.html?id=79d753815619465c9093829d3d8149a8' target='_blank'><b>\"High Water Mark\" Initiative</b>\n",
       "                        </a>\n",
       "                        <br/>\n",
       "                        <br/><b>Summary</b>: Maps, Applications, and related GIS data\n",
       "                        <br/><b>Description</b>: None\n",
       "                        <br/><b>Owner</b>: risson\n",
       "                        <br/><b>Created</b>: August 27, 2018\n",
       "\n",
       "                    </div>\n",
       "                </div>\n",
       "                "
      ],
      "text/plain": [
       "<Group title:\"\"High Water Mark\" Initiative\" owner:risson>"
      ]
     },
     "execution_count": 109,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "urban_groups[1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can expand the query string to include multiple fields on a group such as `owner`, `description` etc. Let us look for groups created and owned by account `esri`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 110,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[<Group title:\"Antarctic Maps\" owner:esri>,\n",
       " <Group title:\"ArcGIS Data and Maps\" owner:esri>,\n",
       " <Group title:\"ArcGIS Online Basemaps\" owner:esri>,\n",
       " <Group title:\"ArcGlobe Basemaps\" owner:esri>,\n",
       " <Group title:\"ArcMap Basemaps\" owner:esri>,\n",
       " <Group title:\"Arctic Maps\" owner:esri>,\n",
       " <Group title:\"China Basemaps for Developers\" owner:esri>,\n",
       " <Group title:\"Community Basemaps\" owner:esri>,\n",
       " <Group title:\"Esri Maps and Data\" owner:esri>,\n",
       " <Group title:\"India Basemaps for Developers\" owner:esri>,\n",
       " <Group title:\"Living Atlas: Community Maps\" owner:esri>,\n",
       " <Group title:\"OpenStreetMap Vector Basemap\" owner:esri>,\n",
       " <Group title:\"Places\" owner:esri>,\n",
       " <Group title:\"Tiled Basemaps\" owner:esri>,\n",
       " <Group title:\"Vector Basemaps\" owner:esri>]"
      ]
     },
     "execution_count": 110,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "esri_owned_groups = ago_gis.groups.search(query='owner:esri and description:basemaps', max_groups=15)\n",
    "esri_owned_groups"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"properties-of-a-group\"></a>\n",
    "## Properties of a group\n",
    "You can query the metadata and related information about a group by querying the properties of its corresponding `Group` object:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'public'"
      ]
     },
     "execution_count": 68,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "esri_group1 = esri_owned_groups[0]\n",
    "esri_group1.access"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let us print some more of the properties of this group"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6cd54e197601410e81a2cbcc9c3e1f22 False True\n",
      "esri\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "time.struct_time(tm_year=2016, tm_mon=6, tm_mday=23, tm_hour=15, tm_min=49, tm_sec=45, tm_wday=3, tm_yday=175, tm_isdst=1)"
      ]
     },
     "execution_count": 111,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import time\n",
    "print(esri_group1.groupid, esri_group1.isFav, esri_group1.isInvitationOnly)\n",
    "print(esri_group1.owner)\n",
    "time.localtime(esri_group1.created/1000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Once you know the `id` of a group, you can access it using the `get()` method of the `GroupManager` object:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 112,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div class=\"9item_container\" style=\"height: auto; overflow: hidden; border: 1px solid #cfcfcf; border-radius: 2px; background: #f6fafa; line-height: 1.21429em; padding: 10px;\">\n",
       "                    <div class=\"item_left\" style=\"width: 210px; float: left;\">\n",
       "                       <a href='https://www.arcgis.com/home/group.html?id=6cd54e197601410e81a2cbcc9c3e1f22' target='_blank'>\n",
       "                        <img src='https://www.arcgis.com/sharing/rest/community/groups/6cd54e197601410e81a2cbcc9c3e1f22/info/Esri_Logo_13.jpg' class=\"itemThumbnail\">\n",
       "                       </a>\n",
       "                    </div>\n",
       "\n",
       "                    <div class=\"item_right\" style=\"float: none; width: auto; overflow: hidden;\">\n",
       "                        <a href='https://www.arcgis.com/home/group.html?id=6cd54e197601410e81a2cbcc9c3e1f22' target='_blank'><b>Antarctic Maps</b>\n",
       "                        </a>\n",
       "                        <br/>\n",
       "                        <br/><b>Summary</b>: This group contains a collection of ready-to-use polar web maps and layers for the Antarctic region that have been published by Esri.\n",
       "                        <br/><b>Description</b>: <br /><div><div>This group contains a collection of web maps and map layers for the Antarctic region that have been published by Esri.  These maps and layers are also part of the <a href='http://doc.arcgis.com/en/living-atlas/#s=0&amp;subCat=0&amp;type=All&amp;area=All' target='_blank'>Living Atlas of the World</a>, the foremost collection of authoritative, ready-to-use global geographic information.</div><div><br /></div><div><br /></div><div><font size='4'>Using Web Maps</font></div><div>The ready-to-use maps in this collection are based on the polar projection WGS_1984_Antarctic_Polar_Stereographic and can be opened or added to applications that support web maps.  </div><div><br /></div><div><br /></div><div><font size='4'>Using Layers </font></div><div>To view layers in this group you'll want to add layers to a map that is using the Polar projection of WGS_1984_Antarctic_Polar_Stereographic, for example the <a href='http://www.arcgis.com/home/item.html?id=6553466517dd4d5e8b0c518b8d6b64cb' target='_blank'>Antarctic Imagery</a> basemap. Other polar projections may be used within their useful limits. </div></div><div><br /></div><div><br /></div><div>Looking for content maps and layers on the other side of the globe?  The <a href='http://www.arcgis.com/home/group.html?id=8ded5dee19d8452aa2a90784dfb9424d' target='_blank'>Arctic Maps</a> group is also available.<br /></div>\n",
       "                        <br/><b>Owner</b>: esri\n",
       "                        <br/><b>Created</b>: June 23, 2016\n",
       "\n",
       "                    </div>\n",
       "                </div>\n",
       "                "
      ],
      "text/plain": [
       "<Group title:\"Antarctic Maps\" owner:esri>"
      ]
     },
     "execution_count": 112,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ago_gis.groups.get(esri_group1.groupid)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"creating-new-groups\"></a>\n",
    "## Creating new groups\n",
    "You can create new groups by calling the `create()` method of the `GroupManager` object. This method is similar to other `create` methods of `ResourceManager` objects and returns you an instance of the `Group` object it created.\n",
    "\n",
    "Let us create a new group for geocaching enthusiasts in our GIS. Replace the credentials below with that of your org which has appropriate privileges to create a group. To learn more about user types, roles and privileges, [click here](https://doc.arcgis.com/en/arcgis-online/administer/user-types-orgs.htm). To learn more about profiles, [see here](https://developers.arcgis.com/python/guide/working-with-different-authentication-schemes/#Storing-your-credentialls-locally)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 154,
   "metadata": {},
   "outputs": [],
   "source": [
    "# connect to GIS with credentials\n",
    "gis = GIS(profile=\"your_online_admin_profile\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 155,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Searching if a group with title 'Recreational geocaching' already exists, if it exists then delete it\n",
    "for gc_group in gis.groups.search(f\"Recreational geocaching AND owner:{gis.users.me.username}\"):\n",
    "    try:\n",
    "        gc_group.delete()\n",
    "    except Exception as e:\n",
    "        pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 156,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div class=\"9item_container\" style=\"height: auto; overflow: hidden; border: 1px solid #cfcfcf; border-radius: 2px; background: #f6fafa; line-height: 1.21429em; padding: 10px;\">\n",
       "                    <div class=\"item_left\" style=\"width: 210px; float: left;\">\n",
       "                       <a href='https://geosaurus.maps.arcgis.com/home/group.html?id=307a504f9eb74648a96352f5b65c6f98' target='_blank'>\n",
       "                        <img src='' ' class=\"itemThumbnail\">\n",
       "                       </a>\n",
       "                    </div>\n",
       "\n",
       "                    <div class=\"item_right\" style=\"float: none; width: auto; overflow: hidden;\">\n",
       "                        <a href='https://geosaurus.maps.arcgis.com/home/group.html?id=307a504f9eb74648a96352f5b65c6f98' target='_blank'><b>Recreational geocaching</b>\n",
       "                        </a>\n",
       "                        <br/>\n",
       "                        <br/><b>Summary</b>: Share your GPX tracks as feature layers here\n",
       "                        <br/><b>Description</b>: Group to share your landmarks and games\n",
       "                        <br/><b>Owner</b>: ArcGISPyAPIBot\n",
       "                        <br/><b>Created</b>: September 19, 2023\n",
       "\n",
       "                    </div>\n",
       "                </div>\n",
       "                "
      ],
      "text/plain": [
       "<Group title:\"Recreational geocaching\" owner:ArcGISPyAPIBot>"
      ]
     },
     "execution_count": 156,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "geocaching_group = gis.groups.create(title='Recreational geocaching',\n",
    "                                    tags = 'hobby, geocaching, gps, hide n seek',\n",
    "                                    description = 'Group to share your landmarks and games',\n",
    "                                    snippet = 'Share your GPX tracks as feature layers here',\n",
    "                                    access = 'org',\n",
    "                                    is_invitation_only = 'False',\n",
    "                                    thumbnail = r'../../static/img/geocaching.jpeg')\n",
    "geocaching_group"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"sharing-content-to-groups\"></a>\n",
    "### Sharing content to groups\n",
    "In an ArcGIS Org, an `Item` can have 4 privacy levels - `private`, `group`, `org`, `everyone`. When an `Item` is shared to a group, all members of a group get to view it. Similarly, when shared to an organization, all authenticated members of the org can view it. When shared to everyone, and if the org permits anonymous access, the item is public and accessible to anyone and does not have to be a logged in user.\n",
    "\n",
    "First, let us add a CSV containing some points to the GIS."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 157,
   "metadata": {},
   "outputs": [],
   "source": [
    "# fetch your username\n",
    "username = gis.users.me.username"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 158,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'ArcGISPyAPIBot'"
      ]
     },
     "execution_count": 158,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "username"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"sharing-content-to-groups\"></a>\n",
    "We're going to create a CSV item called Hidden treasures, but before we do, let's ensure the user doesn't already own one in this portal. If they do, we'll delete it so the subsequent code will work."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 159,
   "metadata": {},
   "outputs": [],
   "source": [
    "for csv_item in gis.content.search(f\"title:Hidden treasures AND owner:{username}\"):\n",
    "    try:\n",
    "        csv_item.delete()\n",
    "    except Exception as e:\n",
    "        pass\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 160,
   "metadata": {},
   "outputs": [],
   "source": [
    "# here we'll add the item titled 'Hidden treasures' with certain properties\n",
    "item_properties = {'title':'Hidden treasures',\n",
    "                  'tags':['geocaching', 'searching', 'hikes', 'POI'],\n",
    "                  'snippet':'Points containing treasures for geocaching activity'}\n",
    "root_folder = gis.content.folders.get()\n",
    "fc_item = root_folder.add(\n",
    "    item_properties, \n",
    "    data='../../samples/05_content_publishers/data/hidden_treasures_geocaching.csv'\n",
    ").result()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 161,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'private'"
      ]
     },
     "execution_count": 161,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fc_item.access"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Items with a `private` sharing level can only be shared to groups the item owner has sharing access to. To share an `Item` to a group, call the `share()` method of the `Item` object and pass the comma separated list of `Group` objects or names of the groups or their IDs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 162,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 162,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# let us share it to the group so other enthusiasts can enjoy this map\n",
    "fc_item.sharing.groups.add(group=geocaching_group)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"managing-your-groups\"></a>\n",
    "## Managing your groups\n",
    "\n",
    "### Listing contents of the group\n",
    "As the first step in managing your groups, let us view the items shared with the group by using the `content()` method"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 122,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[<Item title:\"Hidden treasures\" type:CSV owner:ArcGISPyAPIBot>]"
      ]
     },
     "execution_count": 122,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "geocaching_group.content()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Adding users to the group\n",
    "Now our group has sufficient details and content to make it useful for others. Let us add some users. You can either add users using the `add_users()` method and specify the list of usernames, or if you wish to leave joining to their choice, you can invite them to the group using the `invite_users()` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 139,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'notAdded': []}"
      ]
     },
     "execution_count": 139,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# let us add 2 users to this group\n",
    "geocaching_group.add_users(['user_1', 'user_2'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The method returns a dictionary with information on which users could not be added. As seen on the guide for [managing users](https://developers.arcgis.com/python/guide/accessing-and-managing-users/), users could have custom privileges  preventing them from joining groups. In such occasions, you would get the names of those users in this return list."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Listing users belonging to a group\n",
    "You can list the users in a group by calling the `get_members()` method. The method returns a dictionary which contains the owner of the group, and the list of admin and users."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 140,
   "metadata": {},
   "outputs": [],
   "source": [
    "members_of_group = geocaching_group.get_members()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 141,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'owner': 'ArcGISPyAPIBot',\n",
       " 'admins': ['ArcGISPyAPIBot'],\n",
       " 'users': ['user_1']}"
      ]
     },
     "execution_count": 141,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "members_of_group"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Removing users from a group\n",
    "You can remove users from a group by calling the `remove_users()` method and passing the list of usernames to be removed. The method returns you a dictionary containing those users who cannot be removed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 126,
   "metadata": {},
   "outputs": [],
   "source": [
    "# get the username of the owner of the group\n",
    "owner_of_group_username = members_of_group[\"owner\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's remove a member from the group. We'll return the first user from the users key component of the get_members() output\n",
    "\n",
    "`Note:` If there are no users in the group except the owner and the admin then the following cell will give an output 'No users in this group to remove.'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 142,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'notRemoved': []}\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    first_username_of_group = members_of_group[\"users\"][0]\n",
    "    print(geocaching_group.remove_users([first_username_of_group]))\n",
    "except IndexError as ie:\n",
    "    print(\"No users in this group to remove.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 144,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'owner': 'ArcGISPyAPIBot', 'admins': ['ArcGISPyAPIBot'], 'users': []}"
      ]
     },
     "execution_count": 144,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "geocaching_group.get_members()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's see  if we can remove the owner of the group"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 145,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'notRemoved': ['ArcGISPyAPIBot']}"
      ]
     },
     "execution_count": 145,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "geocaching_group.remove_users([owner_of_group_username])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Thus, you cannot remove the owner or admin of the group until you reassign the ownership to another user.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Updating a group\n",
    "You can update any or all the fields of a group that you specified when creating it. Thus, the `update()` accepts the same parameters as `create()`. Let us close the group to members who can be added through invitation only. This prevents users from sending a joining request.\n",
    "\n",
    "<blockquote><b>Note:</b> Please note that the group ID cannot be updated.</blockquote>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 146,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 146,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "geocaching_group.isInvitationOnly"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 147,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 147,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "geocaching_group.update(is_invitation_only=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 148,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 148,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "geocaching_group.isInvitationOnly"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Terminating a group\n",
    "If a group no longer serves the purpose or if its requirements have changed, the owner and members have a few options. They can leave the group by calling the `leave()` method. When users leave a group, the content they shared with the group will automatically be unshared. The owner of the group or the admin of the organization can delete the group by calling the `delete()` method. \n",
    "\n",
    "However if the contents and the group have to be preserved, the group's ownership can be transferred by calling the `reassign_to()` and specifying the new owner's username. \n",
    "\n",
    "<blockquote><b>Note:</b> Only the administrator of the organization can reassign a group to another user.</blockquote>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "let us reassign ownership to another user"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 149,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'owner': 'ArcGISPyAPIBot',\n",
       " 'admins': ['ArcGISPyAPIBot'],\n",
       " 'users': ['user_1']}"
      ]
     },
     "execution_count": 149,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "members_of_group"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 150,
   "metadata": {},
   "outputs": [],
   "source": [
    "first_username = ''\n",
    "try:\n",
    "    first_username = members_of_group['users'][0]\n",
    "except:\n",
    "    print('No users exist in the group except the owner itself')\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 151,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    print(geocaching_group.reassign_to(target_owner = first_username))\n",
    "except:\n",
    "    print('No other user to reassign the group to')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "if the group got reassigned then we can see that the owner of the group has changed by running the following cell"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 152,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'user_1'"
      ]
     },
     "execution_count": 152,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "group_memebers = geocaching_group.get_members()\n",
    "group_memebers['owner']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "if the group got reassigned then we see that the previous owner now becomes a user in the group"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 153,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'owner': 'user_1',\n",
       " 'admins': ['user_1'],\n",
       " 'users': ['ArcGISPyAPIBot']}"
      ]
     },
     "execution_count": 153,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "geocaching_group.get_members()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, let us delete this group"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 128,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 128,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "geocaching_group.delete()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": false,
   "sideBar": false,
   "skip_h1_title": true,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": true,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
